设为首页收藏本站
开启辅助访问

Python读取指定目录下的指定后缀文件名列表(批量读取)

您所在的位置:网站首页 python 查找文件夹名 Python读取指定目录下的指定后缀文件名列表(批量读取)

Python读取指定目录下的指定后缀文件名列表(批量读取)

2024-07-09 15:23| 来源: 网络整理| 查看: 265

一、获取指定目录下、指定后缀的文件名列表  """ 函数说明:获取指定目录下的、指定后缀的文件 例如:.xlsx、.json Parameters: path - 目录所在的路径 例如 path='D:\Python Example\Tianyancha\Data' suffix - 后缀,例如'.xlsx' Returns: input_template_All - 指定后缀的所有文件名 Author: heda3 Blog: https://blog.csdn.net/heda3 Modify: 2019-10-12 """ #参考:https://www.runoob.com/python/os-listdir.html def getFileName1(path,suffix): # 获取指定目录下的所有指定后缀的文件名 input_template_All=[] f_list = os.listdir(path)#返回文件名 for i in f_list: # os.path.splitext():分离文件名与扩展名 if os.path.splitext(i)[1] ==suffix: input_template_All.append(i) #print(i) return input_template_All 二、(升级版)获取指定目录下指定后缀的文件名列表和文件名+目录的拼接 

例如:D:\Python Example\Tianyancha\Data\xx.xlsx

""" 函数说明:获取指定目录下的、指定后缀的文件名及路径+文件名的拼接 例如:.xlsx、.json Parameters: path - 目录所在的路径 例如 path='D:\Python Example\Tianyancha\Data' suffix - 后缀,例如'.xlsx' Returns: input_template_All - 指定后缀的所有文件名 xx.xlsx input_template_All_Path - 文件名和该路径的拼接 例如:D:\Python Example\Tianyancha\Data\xx.xlsx Author: heda3 Blog: https://blog.csdn.net/heda3 Modify: 2019-10-12 """ #参考:https://www.runoob.com/python/os-walk.html def getFileName2(path,suffix): input_template_All=[] input_template_All_Path=[] for root, dirs, files in os.walk(path, topdown=False): for name in files: #print(os.path.join(root, name)) print(name) if os.path.splitext(name)[1] == suffix: input_template_All.append(name) input_template_All_Path.append(os.path.join(root, name)) return input_template_All,input_template_All_Path

测试案例:

import os path='D:\Python Example\Tianyancha\Data' input_template_All1=getFileName1(path,'.xlsx') input_template_All2,input_template_All_Path2=getFileName2(path,'.xlsx')

可更该为获取当前目录:

os.path.abspath('.')#获取当前工作目录路径 介绍其它获取方法https://www.cnblogs.com/Jomini/p/8636129.html

 

参考文档:

【1】Python os.listdir() 方法 https://www.runoob.com/python/os-listdir.html

【2】Python os.walk() 方法 https://www.runoob.com/python/os-walk.html

【3】os.path.split(path) 把路径分割成 dirname 和 basename,返回一个元组 

os.path.join(path1[, path2[, ...]]) 把目录和文件名合成一个路径

Python os.path() 模块(全)  https://www.runoob.com/python/python-os-path.html

walk()方法语法格式如下:

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) 参数

top -- 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。

root 所指的是当前正在遍历的这个文件夹的本身的地址dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)

topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。

onerror -- 可选,需要一个 callable 对象,当 walk 需要异常时,会调用。

followlinks -- 可选,如果为 True,则会遍历目录下的快捷方式(linux 下是软连接 symbolic link )实际所指的目录(默认关闭),如果为 False,则优先遍历 top 的子目录。

返回值

该方法没有返回值。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3